<!-- 实习生证明模板 -->
<template>
  <ContentCard>
    <template #header>
      <PageHeaderNew
        title="工作证明开具模板方案配置"
        :breadCrumb="[
          '人事',
          '基础设置',
          '工作管理',
          '工作证明开具模板方案配置'
        ]"
        :showBack="true"
      >
      </PageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-input-search
          v-model="nameSearch"
          placeholder="请输入模板名称，按下回车可以搜索"
          :style="{
            width: '300px'
          }"
          search-button
          @search="onSearch"
          @press-enter="onSearch"
        >
          <icon-search />
        </a-input-search>
      </template>
      <template #right>
        <a-button type="primary" @click="goInternshipTemplateDetail">
          新增模板
        </a-button>
        <a-button type="outline" @click="del(null)" status="danger">
          批量删除
        </a-button>
      </template>
    </ConditionBox>
    <TableTurn
      :args="args"
      ref="tableRef"
      :tableData="getInternshipTemplateData"
      style="margin-top: 20px"
    >
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <a-table-column :width="150" title="模板名称" dataIndex="name">
      </a-table-column>
      <a-table-column :width="150" title="模板说明" dataIndex="remark">
      </a-table-column>
      <a-table-column :width="150" title="模板页面方向" dataIndex="direction">
        <template #cell="{ record }">
          {{ record.direction === 1 ? '纵版' : '横版' }}
        </template>
      </a-table-column>
      <a-table-column title="是否启用" data-index="enable" :width="150">
        <template #cell="{ record: { enable } }">
          <a-tag
            class="enable"
            :color="
              enable === 1 ? `rgb(var(--green-1))` : 'rgb(var(--danger-1))'
            "
            :style="{
              color:
                enable === 1 ? `rgb(var(--green-6))` : 'rgb(var(--danger-6))',
              '--enable':
                enable === 1 ? `rgb(var(--green-6))` : 'rgb(var(--danger-6))'
            }"
          >
            {{ enable === 1 ? '启用' : '停用' }}
          </a-tag>
        </template>
      </a-table-column>
      <a-table-column
        :width="200"
        title="是否为默认模板"
        dataIndex="isShowDefault"
      >
        <template #cell="{ record }">
          <a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="record.isShowDefault"
            @change="stateChange(record)"
          />
        </template>
      </a-table-column>
      <a-table-column title="操作" :width="100" fixed="right">
        <template #cell="{ record }">
          <div style="float: left; display: flex">
            <a-tooltip content="预览">
              <icon-eye
                size="26"
                @click="goPreview(record)"
                style="color: #5085ff; cursor: pointer"
              />
            </a-tooltip>
            <a-tooltip content="复制">
              <IconFont
                type="icon-fuzhi"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goCopy(record)"
              />
            </a-tooltip>
            <a-tooltip content="编辑">
              <IconFont
                type="icon-edit"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="goInternshipTemplateDetail(record)"
              />
            </a-tooltip>
            <a-tooltip content="删除" position="left">
              <a-popconfirm content="是否确认删除该条数据?" @ok="del(record)">
                <IconFont
                  type="icon-delete"
                  :size="26"
                  :style="{
                    cursor: 'pointer'
                  }"
                />
              </a-popconfirm>
            </a-tooltip>
          </div>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <PreviewModal v-model:visible="previewVisible" :data="currData" />
  <CopyModal
    v-model:visible="copyVisible"
    @copy-emit="copyEmit"
    @copyEditEmit="copyEditEmit"
    :validateFun="validateNameToCopy"
  />
</template>
<script setup lang="ts">
import {
  GetInternshipProofTemplate,
  PutInternshipProofTemplateState,
  DelInternshipProofTemplate,
  PostInternshipProofTemplate,
  CheckInternshipProofTemplate
} from '@/apis/management/human/baseSetting/certificateSetting';
import { useRouter } from 'vue-router';
import { Message, Modal } from '@arco-design/web-vue';
import PreviewModal from '../Components/Preview/index.vue';
import { validateRules } from '@/utils/common';
import { cloneDeep } from 'lodash';
const router = useRouter();

let tableRef = ref(); // 储存table的ref
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);
const selectedListData = computed(() => tableRef.value.selectedListData);

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  }
});
const templateList = ref();
let nameSearch = ref('');
//获取实习生证明模板列表
const getInternshipTemplateData = async (pageData?: any) => {
  const res = await GetInternshipProofTemplate({
    ...pageData,
    name: nameSearch.value,
    type: 3 //
  });
  return Promise.resolve(res);
};

const onSearch = () => {
  refresh();
};

//修改默认模板
const stateChange = async (record: any) => {
  if (record.isShowDefault === 2) Message.error('必须拥有一个默认模板！');
  else
    await PutInternshipProofTemplateState({
      id: record.id,
      type: 3
    });
  refresh();
};
let previewVisible = ref(false);
let currData = ref();
let preName = ''; //  储存修改之前的名字
const goPreview = (record: any) => {
  currData.value = record;
  previewVisible.value = true;
};

let copyVisible = ref(false);
// 显示复制弹窗
const goCopy = (record: any) => {
  copyVisible.value = true;
  currData.value = cloneDeep(record);
};
// // 复制
const copyEmit = async (record: any) => {
  try {
    currData.value.name = record.name;
    currData.value.isShowDefault = 2;
    currData.value.type = 3;
    delete currData.value.createdAt;
    delete currData.value.id;
    await PostInternshipProofTemplate(currData.value);
    Message.success('复制成功');
    refresh();
    console.log(record);
  } catch (error: unknown) {
    console.log(error);
  }
};

const copyEditEmit = (record: any) => {
  goInternshipTemplateDetail(currData.value, record.name);
};

const validateNameToCopy = async (name: string, cb: any) => {
  try {
    if (currData.value?.id && preName === name) {
      //
    } else {
      const data = {
        name,
        type: 3
      };
      const res = await validateRules(CheckInternshipProofTemplate, data);
      return Promise.resolve(res);
    }
  } catch (error: unknown) {
    console.log(error);
  }
};
//去新增或编辑模板
const goInternshipTemplateDetail = (data1?: any, name?: string) => {
  const data = cloneDeep(data1);
  preName = data.name;
  let id = data && data.id! > 0 ? data.id : void 0;
  if (name) {
    preName = name;
    data.name = name;
    data.isShowDefault = 2;
    data.type = 3;
    data.id = void 0;
    delete data.createdAt;
  }
  router.push({
    name: 'WorkProofTemplateDetail',
    query: {
      ...data,
      isCopy: name ? true : false
    }
  });
};
//编辑
const edit = (data: any) => {
  goInternshipTemplateDetail({ id: data.id });
};
//删除
const del = async (record: any) => {
  try {
    if (!record) {
      if (selectedList.value.length === 0) {
        Message.error('请至少选择一项！');
      } else {
        Modal.confirm({
          title: '提示',
          content: '确定要删除选中的数据吗？',
          onOk: async () => {
            try {
              if (
                selectedListData.value.find(
                  (item: any) => item.isShowDefault === 1
                )
              ) {
                Message.error('默认模板不能删除！');
              } else {
                await DelInternshipProofTemplate({
                  ids: selectedList.value
                });
                tableRef.value.selectedList = [];
                refresh();
              }
            } catch (error: unknown) {
              console.log(error);
            }
          }
        });
      }
    } else {
      if (record.isShowDefault === 1) Message.error('默认模板不能删除！');
      else {
        await DelInternshipProofTemplate({
          ids: [record.id]
        });
        tableRef.value.selectedList = [];
        refresh();
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const refresh = () => {
  tableRef.value.loadData();
};
</script>
<style lang="less" scoped>
.base-setting-warp {
  padding: 10px 20px;
}
.enable::before {
  content: '';
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  position: relative;
  right: 3px;
  background-color: var(--enable);
}
</style>
